package com.beck.bee.controller;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by cdliubei@jd.com on 4/4/2017.
 */
public class SelectorController {

    public static void main(String[] args) throws IOException {
        Selector selector = null;
        try {
            selector = Selector.open();
            ServerSocketChannel channel= ServerSocketChannel.open();
            channel.configureBlocking(false);
            channel.socket().bind(new InetSocketAddress(7980));
            channel.register(selector, SelectionKey.OP_ACCEPT);
            while(true) {
                System.out.println("before select");
                int readyChannels = selector.select();
                System.out.println("after select");
                if(readyChannels == 0) continue;
                Set selectedKeys = selector.selectedKeys();
                Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
                while(keyIterator.hasNext()) {
                    SelectionKey selectionKey = keyIterator.next();
                    if (selectionKey.isAcceptable()) { // 如果是Accept事件
                        // 获取注册的ServerSocketChannel
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = serverSocketChannel.accept(); // 建立连接
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ); // 注册该连接的Read事件
                        System.out.println("Connected: " + socketChannel.socket().getRemoteSocketAddress());
                    } else if (selectionKey.isReadable()) { // 如果是Read事件
                        // 获取注册的SocketChannel
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        while (socketChannel.read(buffer) > 0) { // 读取接收到的数据
                            buffer.flip();
                            byte[] dst = new byte[buffer.limit()];
                            buffer.get(dst);
                            System.out.println(new String(dst));
                        }
                    }
                    keyIterator.remove(); // 需要将处理过的事件移除
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (selector != null){
                selector.close();
            }
        }

    }
}
